package com.magold.circuit;


import java.util.LinkedList;

import com.magold.algorithm.Node;
import com.magold.circuit.module.CircuitModule;
import com.magold.circuit.state.CircuitState;

public class CircuitNode extends Node<CircuitModule> implements CircuitModule, PathStateListener {
	public static enum CurrentTrend {
		SHOULD_BEGIN, SHOULD_END, KEEP
	}
	private LinkedList<ICircuitPath> mPaths;
	private boolean mPassingCurrent;
	private CurrentTrend mCurrentTrend;

	public CircuitNode(CircuitModule pElement) {
		super(pElement);
		resetTrend();
		mPaths = new LinkedList<ICircuitPath>();
	}

	public CurrentTrend getCurrentTrend() {
		return mCurrentTrend;
	}

	public void resetTrend() {
		mCurrentTrend = CurrentTrend.KEEP;
	}

	@Override
	public void setID(int pID) {
		mElement.setID(pID);
	}

	@Override
	public int getID() {
		return mElement.getID();
	}
	
	@Override
	public boolean isConnected() {
		return mElement.isConnected();
	}

	@Override
	public void onCurrentBegin() {
		mPassingCurrent = true;
		mElement.onCurrentBegin();
	}

	@Override
	public void onPathJoined(ICircuit pCircuit, ICircuitPath pPath) {
		mElement.onPathJoined(pCircuit, pPath);
		pPath.registerListener(this);
		mPaths.add(pPath);
	}

	@Override
	public void onCurrentEnd() {
		mPassingCurrent = false;
		mElement.onCurrentEnd();
	}

	@Override
	public void onPathConnected(ICircuitPath pCircuitPath) {
		if (!mPassingCurrent && mPaths.indexOf(pCircuitPath) >= 0) {
			mCurrentTrend = CurrentTrend.SHOULD_BEGIN;
		}
	}

	@Override
	public void onPathDisconnected(ICircuitPath pCircuitPath) {
		if (!mPassingCurrent) return;

		for (ICircuitPath path : mPaths) {
			if (path.getCurrentState() == CircuitState.RUNNING) {
				return;
			}
		}

		mCurrentTrend = CurrentTrend.SHOULD_END;
	}

	@Override
	public void onPathShortCutted(ICircuitPath pCircuitPath) {
		onPathDisconnected(pCircuitPath);
	}

	@Override
	public void onPathPowerOff(ICircuitPath pCircuitPath) {
		onPathDisconnected(pCircuitPath);
	}
	
	public boolean isPassingCurrent() {
		return mPassingCurrent;
	}

	@Override
	public float[] getWireInPosition() {
		return mElement.getWireInPosition();
	}

	@Override
	public float[] getWireOutPosition() {
		return mElement.getWireOutPosition();
	}

}